package com.stylefeng.wap;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.util.PasswordEncoder;
import com.stylefeng.guns.modular.shop.service.*;
import com.stylefeng.guns.persistence.shop.model.TGoods;
import com.stylefeng.guns.persistence.shop.model.TGoodsClass;
import com.stylefeng.guns.persistence.shop.model.TMember;
import com.stylefeng.web.utils.JSONSerializerUtil;
import com.stylefeng.web.utils.MemberUtils;
import com.stylefeng.web.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


/**
	 * 
	 * @author zsCat 2016-10-31 14:01:30
	 * @Email: 951449465@qq.com
	 * @version 4.0v
	 *	商品管理
	 */
@Controller
@RequestMapping("/wap")
public class Wap1IndexController extends BaseController{

	@Resource
	private ITGoodsClassService TGoodsClassService;
	@Resource
	private ITGoodsService TGoodsService;

	@Resource
	private ITFloorService floorService;
	RedisUtils redisUtils = new RedisUtils();
	@Resource
	private ITGoodsTypeService TGoodsTypeService;

	@Resource
	ITMemberService itMemberService;
	 @RequestMapping("")
	  public ModelAndView index(HttpServletRequest req) {
	        try {
	            ModelAndView model = new ModelAndView("/wap/index.html");

				if (MemberUtils.getSessionLoginUser()!=null){
					model.addObject("city", MemberUtils.getSessionLoginUser().getUsername());
				}else{
					model.addObject("city", "未登录");
				}
	            return model;
	        } catch (Exception e) {
	            e.printStackTrace();
	            throw new RuntimeException("导航失败!");
	        }
	    }
	 @RequestMapping("/goodsDetail/{id}")
		public ModelAndView goodsDetail(@PathVariable("id") Long id,HttpServletRequest req)throws Exception{
			ModelAndView mav=new ModelAndView();
			TGoods goods=TGoodsService.selectById(id);
			mav.addObject("goods", goods);
			if(goods.getImgmore()!=null && goods.getImgmore().indexOf(",")>-1){
				mav.addObject("imgs", goods.getImgmore().split(","));
			}
			mav.setViewName("wap/goodsDetail.html");
			goods.setClickHit(goods.getClickHit()+1);
			TGoodsService.updateById(goods);
			//查询详情商品的 其他商品
			TGoods p=new TGoods();
			p.setCreateBy(goods.getCreateBy());

		    EntityWrapper<TGoods> ew = new EntityWrapper<>(p);

			mav.addObject("ownGoods", TGoodsService.selectList(ew));

			return mav;
		}

	 @RequestMapping("/information/{createBy}")
	  public ModelAndView information(@PathVariable("createBy") Long createBy) {
		 ModelAndView model = new ModelAndView("/wap/person/information.html");
        TMember member=itMemberService.selectById(createBy);
        model.addObject("member", member);
		 return model;
	 }
	 /**
	  * 商城公告
	  * @param
	  * @return
	  */
	 @RequestMapping("/newD/{id}")
	  public ModelAndView newD(@PathVariable("id") Long id) {
		 ModelAndView model = new ModelAndView("/wap/person/blog");
//        Article article=articleService.selectByPrimaryKey(id);
//        model.addObject("article", article);
//        List<Article> articleList=articleService.select(new Article());
//        model.addObject("articleList", articleList);
		 return model;
	 }
	   /**
		 * 跳转到登录页面
		 * 
		 * @return
		 */

	@RequestMapping(value = "login")
	public ModelAndView toLogin1() {
		ModelAndView model = new ModelAndView("/wap/login.html");
		if( this.getSessionLoginUser() != null){
			return new ModelAndView("redirect:/wap");
		}
		return model;
	}

		/**
		 * 登录验证
		 * 
		 * @param username
		 * @param password
		 * @param
		 * @return
		 */
		@RequestMapping(value = "login", method = RequestMethod.POST)
		public @ResponseBody Map<String, Object> checkLogin(String username,
				String password,  HttpServletRequest request) {

			Map<String, Object> msg = new HashMap<String, Object>();
			HttpSession session = request.getSession();
			//code = StringUtils.trim(code);
			username = StringUtils.trim(username);
			password = StringUtils.trim(password);

			TMember user = itMemberService.checkUser(username, password);
			if (null != user) {
				EntityWrapper<TMember> mb = new EntityWrapper<>(user);
				session.setAttribute(MemberUtils.SESSION_LOGIN_MEMBER, itMemberService.selectOne(mb));
			} else {
				msg.put("error", "用户名或密码错误");
			}
			return msg;
		}
	 
		 /**
		 * 跳转到登录页面
		 * 
		 * @return
		 */
		@RequestMapping(value = "reg", method = RequestMethod.GET)
		public String reg() {
			if( this.getSessionLoginUser() != null){
				return "redirect:/wap";
			}
			return "/wap/register.html";
		}
	
		@RequestMapping(value = "reg", method = RequestMethod.POST)
		public @ResponseBody Map<String, Object> reg(
				@RequestParam(value = "password",required=true)String  password,
				@RequestParam(value = "email",required=false)String email,
				@RequestParam(value = "phone",required=false)String phone,
				@RequestParam(value = "username")String username,
				@RequestParam(value = "passwordRepeat",required=true)String passwordRepeat,HttpServletRequest request) {
			Map<String, Object> msg = new HashMap<String, Object>();
			if (!StringUtils.equalsIgnoreCase(password, passwordRepeat)) {
				msg.put("error", "密码不一致!");
				return msg;
			}
			String secPwd = null ;
			TMember m=new TMember();
			secPwd = PasswordEncoder.encrypt(password, username);
			m.setUsername(username);
			m.setPassword(secPwd);
			m.setTrueName(m.getUsername());
			m.setPhone(phone);
			try {
				HttpSession session = request.getSession();
				boolean result = itMemberService.insert(m);
				System.out.println(m.getId());
				if (result) {
					EntityWrapper<TMember> mb = new EntityWrapper<>(m);
					session.setAttribute(MemberUtils.SESSION_LOGIN_MEMBER, itMemberService.selectOne(mb));
				} else {
					msg.put("error", "注册失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return msg;
		}
	 	/**
		 * 用户退出
		 * 
		 * @return 跳转到登录页面
		 */
		@RequestMapping("logout")
		public String logout(HttpServletRequest request) {
			request.getSession().invalidate();
			return "redirect:/wap/login";
		}
	

}
